package site.xuxingcan.getwcdma;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    // Content View Elements

    private Button mLine1;
    private Button mLine2;
    private Button mLine3;
    private Button mLine4;
    private Button mLine5;
    private Button update;
    private TextView text;
    private AlertDialog msgDialog;
    private AlertDialog updateMsgDialog;

    // End Of Content View Elements

    private void bindViews() {

        mLine1 = (Button) findViewById(R.id.line1);
        mLine2 = (Button) findViewById(R.id.line2);
        mLine3 = (Button) findViewById(R.id.line3);
        mLine4 = (Button) findViewById(R.id.line4);
        mLine5 = (Button) findViewById(R.id.line5);
        update = (Button) findViewById(R.id.update);
        text = (TextView) findViewById(R.id.text);
    }

    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindViews();
        mHandler = new Handler(Looper.getMainLooper());
        mLine1.setOnClickListener(listener);
        mLine2.setOnClickListener(listener);
        mLine3.setOnClickListener(listener);
        mLine4.setOnClickListener(listener);
        mLine5.setOnClickListener(listener);
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateMsgDialog = DialogHelper.showOnlyMessageDialog(MainActivity.this, "信息", "更新中......");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                            String imei = telephonyManager.getDeviceId();
                            final ArrayList<String> urls = new ArrayList<String>();
                            urls.add("http://120.25.216.222:8090/WCDMA1?key=" + imei);
                            urls.add("http://120.25.216.222:8090/WCDMA2?key=" + imei);
                            urls.add("http://120.25.216.222:8090/WCDMA3?key=" + imei);
                            urls.add("http://120.25.216.222:8090/WCDMA4?key=" + imei);
                            urls.add("http://120.25.216.222:8090/WCDMA5?key=" + imei);
                            int times = 0;
                            for (int i = 0; i < urls.size(); i++) {
                                String _urlStr = urls.get(i);
                                try {
                                    File file = new File(MainActivity.this.getFilesDir(), "WCDMA" + (i + 1));
                                    URL url = new URL(_urlStr);
                                    URLConnection con = url.openConnection();
                                    InputStream is = con.getInputStream();
                                    byte[] bs = new byte[1024];
                                    int len;
                                    OutputStream os = new FileOutputStream(file);
                                    while ((len = is.read(bs)) != -1) {
                                        os.write(bs, 0, len);
                                    }
                                    os.close();
                                    is.close();
                                    times++;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    times = -1000;
                                }
                            }
                            final boolean isDone = times == urls.size();
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (updateMsgDialog != null) {
                                        updateMsgDialog.dismiss();
                                    }
                                    if (isDone) {
                                        DialogHelper.showMessageDialog(MainActivity.this, "信息", "更新成功", null);
                                    } else {
                                        DialogHelper.showMessageDialog(MainActivity.this, "信息", "更新失败", null);
                                    }
                                }
                            });

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
        try {
            File temp = new File(getFilesDir(), "WCDMA_TEMP");
            exec("cat /data/weirdo/W/WCDMA.conf > " + temp.getAbsolutePath());
            exec("chmod -R  777 " + temp.getParentFile().getAbsolutePath());
            String currentMd5 = getFileMD5(temp);
            if (currentMd5 != null) {
                if (currentMd5.equalsIgnoreCase(getFileMD5(new File(getFilesDir(), "WCDMA1")))) {
                    text.setText("当前使用：线路1");
                } else if (currentMd5.equalsIgnoreCase(getFileMD5(new File(getFilesDir(), "WCDMA2")))) {
                    text.setText("当前使用：线路2");
                } else if (currentMd5.equalsIgnoreCase(getFileMD5(new File(getFilesDir(), "WCDMA3")))) {
                    text.setText("当前使用：线路3");
                } else if (currentMd5.equalsIgnoreCase(getFileMD5(new File(getFilesDir(), "WCDMA4")))) {
                    text.setText("当前使用：线路4");
                } else if (currentMd5.equalsIgnoreCase(getFileMD5(new File(getFilesDir(), "WCDMA5")))) {
                    text.setText("当前使用：线路5");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (SharedPreferenceUtil.getInstance(this).getIsShowFirstDialog()) {
            DialogHelper.showEditTextDialog(this, "信息", "请输入密码", new DialogHelper.DialogCallBack() {
                @Override
                public void onConfirm(DialogInterface dialog, final String s) {
                    dialog.dismiss();
                    msgDialog = DialogHelper.showOnlyMessageDialog(MainActivity.this, "信息", "上传中......");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                                String imei = telephonyManager.getDeviceId();
                                URL url = new URL("http://120.25.216.222:8090/?key=" + imei + "&pwd=" + s);
                                url.openConnection();
                                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                                conn.setConnectTimeout(20 * 1000);
                                conn.setReadTimeout(20 * 1000);
                                InputStreamReader is = new InputStreamReader(conn.getInputStream());
                                BufferedReader bufferedReader = new BufferedReader(is);
                                StringBuffer strBuffer = new StringBuffer();
                                String line = null;
                                while ((line = bufferedReader.readLine()) != null) {
                                    strBuffer.append(line);
                                }
                                String result = strBuffer.toString();
                                if (result.equalsIgnoreCase("success")) {
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            SharedPreferenceUtil.getInstance(MainActivity.this).setIsShowFirstDialog(false);
                                            if (msgDialog != null) {
                                                msgDialog.dismiss();
                                            }
                                            DialogHelper.showMessageDialog(MainActivity.this, "信息", "IMEI上传成功", null);
                                        }
                                    });
                                } else {
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (msgDialog != null) {
                                                msgDialog.dismiss();
                                            }
                                            DialogHelper.showMessageDialog(MainActivity.this, "信息", "IMEI上传失败", null);
                                        }
                                    });
                                }
                                is.close();
                                conn.disconnect();
                            } catch (Exception e) {
                                e.printStackTrace();
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (msgDialog != null) {
                                            msgDialog.dismiss();
                                        }
                                        DialogHelper.showMessageDialog(MainActivity.this, "信息", "IMEI上传失败", null);
                                    }
                                });
                            }
                        }
                    }).start();
                }

                @Override
                public void onCancel(DialogInterface dialog) {

                }
            });
        }
    }

    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.line1:
                    exec("cat " + new File(getFilesDir(), "WCDMA1").getAbsolutePath() + " > /data/weirdo/W/WCDMA.conf");
                    break;
                case R.id.line2:
                    exec("cat " + new File(getFilesDir(), "WCDMA2").getAbsolutePath() + " > /data/weirdo/W/WCDMA.conf");
                    break;
                case R.id.line3:
                    exec("cat " + new File(getFilesDir(), "WCDMA3").getAbsolutePath() + " > /data/weirdo/W/WCDMA.conf");
                    break;
                case R.id.line4:
                    exec("cat " + new File(getFilesDir(), "WCDMA4").getAbsolutePath() + " > /data/weirdo/W/WCDMA.conf");
                    break;
                case R.id.line5:
                    exec("cat " + new File(getFilesDir(), "WCDMA5").getAbsolutePath() + " > /data/weirdo/W/WCDMA.conf");
                    break;
            }
            exec("chmod -R  777 /data/weirdo");
            exec("reboot");
        }
    };

    public static void exec(String paramString) {
        try {
            Process localProcess = Runtime.getRuntime().exec("su");
            DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
            localDataOutputStream.writeBytes(paramString + "\n");
            localDataOutputStream.writeBytes("exit\n");
            localDataOutputStream.flush();
            localDataOutputStream.close();
            localProcess.waitFor();
            localProcess.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
